<?php

namespace user;
use View;
use Response;
use BaseController;
use Auth;
use User;
use Message;
use Input;
use Validator;
use Redirect;
use DB;

class MessageController extends BaseController {

	public function index(){

        $user_messages = DB::table('messages')->orWhere('to_user_id',Auth::id())->orWhere('from_user_id',Auth::id())->where('message_type','1')->groupBy('to_user_id')->orderBy('created_at','desc')->paginate(2);
        $system_messages = DB::table('messages')->where('message_type','2')->orWhere('to_user_id',Auth::id())->orWhere('from_user_id',Auth::id())->groupBy('to_user_id')->orderBy('created_at','desc')->paginate(2);

		return View::make('user.message.index')->with('title','留言管理')->with('user_messages',$user_messages)->with('system_messages',$system_messages);
	}

	public function lists($id){
        $messages = DB::table('messages')->where('to_user_id',Auth::id())->orWhere('from_user_id',Auth::id())->orderBy('created_at','desc')->paginate(2);
		return View::make('user.message.lists')->with('messages',$messages)->with('title','留言管理');
	}

    /**
     * 开始发送留言
     * @return [type] [description]
     */
    public function doSend(){

        //根据用户名验证用户是否存在
        $user = DB::table('users')->where('username',Input::get('to_user_id'))->first();
        if(!$user){
            return Response::json(array('type'=>'danger','content'=>'用户不存在','data'=>''));
        }

        $rules = array(
            'to_user_id' =>'required|max:20',
            'message_content' => 'required'
        );

        $validator = Validator::make(Input::all(),$rules);
        if($validator->passes()){
            $message = Message::create(Input::only('to_user_id','message_content'));
            $message->to_user_id = (int) $user->id;
            $message->message_type = 1;
            $message->from_user_id = Auth::id();
            if($message->save()){
                return Response::json(array('type'=>'success','content'=>'留言发送成功','data'=>''));
            }else{
                return Response::json(array('type'=>'danger','content'=>'留言发送失败','data'=>''));
            }
        }else{
            return Response::json(array('type'=>'danger','content'=>'留言格式不正确','data'=>''));
        }
    }

    public function clear(){
        $message_type = (int) Input::get('type');

        //判断消息类型是否符合
        if(!in_array($message_type,array(1,2))){
            return Response::json(array('type'=>'success','content'=>'清空失败','data'=>''));
        }

        $message = DB::table('messages')->where('message_type',$message_type)->orWhere('to_user_id',Auth::id())->orWhere('from_user_id',Auth::id())->delete();
        if($message){
            return Response::json(array('type'=>'success','content'=>'清空成功','data'=>''));
        }else{
            return Response::json(array('type'=>'success','content'=>'清空失败','data'=>''));
        }
    }
}
